package com.fy56.platform.logistics.service.impl;

import com.alibaba.fastjson.JSON;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.mapper.CompanyMapper;
import com.fy56.platform.logistics.mapper.MiniProgramMapper;
import com.fy56.platform.logistics.mapper.PayOrderMapper;
import com.fy56.platform.logistics.model.Company;
import com.fy56.platform.logistics.model.MiniProgram;
import com.fy56.platform.logistics.model.Order;
import com.fy56.platform.logistics.model.PayOrder;
import com.fy56.platform.logistics.service.web.IMiniProgramService;
import com.fy56.platform.logistics.service.wx.ICompanyInfoService;
import com.fy56.platform.logistics.service.wx.IOrderService;
import com.fy56.platform.logistics.service.wx.IPayOrderService;
import com.fy56.platform.logistics.utils.DateUtil;
import com.fy56.platform.logistics.utils.HttpClientUtils;
import com.fy56.platform.logistics.utils.MD5Util;
import com.fy56.platform.logistics.utils.StringUtil;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PayOrderServiceImpl  implements IPayOrderService {

    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private IMiniProgramService iMiniProgramService;
    @Autowired
    private ICompanyInfoService iCompanyInfoService;
    @Autowired
    private IOrderService iOrderService;

    @Override
    public PayOrder selectByPrimaryKey(Long id) {
        return payOrderMapper.selectByPrimaryKey(id);
    }

    @Override
    public PayOrder get(PayOrder entity) {
        List<PayOrder> payOrderList = payOrderMapper.findList(entity);
        PayOrder payOrder = null;
        try {
            if (payOrderList != null && payOrderList.size() > 0) {
                payOrder = payOrderList.get(0);
                MiniProgram miniProgram = entity.getMiniProgram();
                Company company = entity.getCompany();

                // 1 查询交易中心 订单状态
                Map<String, String> params = Maps.newHashMap();
                params.put("password", company.getTenantPass());
                params.put("loginName", company.getCode());
                params.put("consumeDetailNo", payOrder.getConsumeDetailNo());
                String postResult = HttpClientUtils.post(miniProgram.getTradingcenterUrl() + "/consumeDetailManager/queryTradeDetail", params, null, 10000, 10000);

                // 2 解析结果封装返回值
                if(StringUtils.isNotEmpty(postResult)){
                    Map<String,Object> resultMap = JSON.parseObject(postResult);
                    Object success = resultMap.get("success");
                    if(Boolean.valueOf(success.toString())){
                        Map<String,Object> objectMap = JSON.parseObject(resultMap.get("object").toString());
                        if(objectMap != null && !objectMap.isEmpty()){

                            // 将接口返回的结果 封装到payOrder中
                            payOrder.setConsumeDetailId(objectMap.get("consumeDetailId")!= null?objectMap.get("consumeDetailId").toString():"");
                            payOrder.setSources(objectMap.get("sources")!= null?objectMap.get("sources").toString():"");
                            payOrder.setConsumeCompanyId(objectMap.get("consumeCompanyId")!= null?objectMap.get("consumeCompanyId").toString():"");
                            payOrder.setConsumeCompanyName(objectMap.get("consumeCompanyName")!= null?objectMap.get("consumeCompanyName").toString():"");
                            payOrder.setConsumeCompanyCode(objectMap.get("consumeCompanyCode")!= null?objectMap.get("consumeCompanyCode").toString():"");
                            payOrder.setStateFlag(objectMap.get("stateFlag")!= null? Integer.parseInt(objectMap.get("stateFlag").toString()):0);
                            payOrder.setTradeType(objectMap.get("tradeType")!= null? objectMap.get("tradeType").toString(): "");
                            payOrder.setConsumeType(objectMap.get("consumeType")!= null? objectMap.get("consumeType").toString(): "");
                            payOrder.setNotifyFlag(objectMap.get("notifyFlag")!= null? Integer.parseInt(objectMap.get("notifyFlag").toString()):0);
                        }
                    }
                }
                System.out.println("交易中心-按交易单号查询交易明细结果：" + postResult);
            }
        }catch (Exception ex){
            throw new RuntimeException(ex);
        }
        return payOrder;
    }

    @Override
    public ResultModel findPayOrderListService(PayOrder entity){
        List<PayOrder> payOrderList = payOrderMapper.findList(entity);
        Map<String, Object> resultMap = Maps.newHashMap();
        if(payOrderList != null && payOrderList.size() > 0){
            resultMap.put("size", payOrderList.size());
            resultMap.put("list", payOrderList);
        }else{
            resultMap.put("size", 0);
            resultMap.put("list", payOrderList);
        }
        return new ResultModel(100,  "支付订单列表查询成功",resultMap);
    }

    @Override
    public ResultModel updateClosePayOrder(PayOrder entity) {
        ResultModel result = null;
        List<PayOrder> payOrderList = payOrderMapper.findList(entity);
        try {
            if (payOrderList != null && payOrderList.size() > 0) {
                MiniProgram miniProgram = entity.getMiniProgram();
                Company company = entity.getCompany();

                PayOrder payOrder = payOrderList.get(0);
                // 1 查询交易中心 订单状态
                Map<String, String> params = Maps.newHashMap();
                params.put("password",  company.getTenantPass());
                params.put("loginName", company.getCode());
                params.put("consumeDetailNo", payOrder.getConsumeDetailNo());
                String postResult = HttpClientUtils.post(miniProgram.getTradingcenterUrl() + "/consumeDetailManager/closeConsumeOrder", params, null, 20000, 20000);

                // 2 解析结果封装返回值
                if(StringUtils.isNotEmpty(postResult)){
                    Map<String,Object> resultMap = JSON.parseObject(postResult);
                    Object success = resultMap.get("success");
                    if(Boolean.valueOf(success.toString())){
                        Date currentDate = new Date();

                        payOrder.setCloseState(1);
                        payOrder.setExpireTime(currentDate);
                        payOrder.setCloseTime(currentDate);
                        int count = payOrderMapper.updateSelective(payOrder);
                        if(count > 0){
                            result = new ResultModel(100,  "支付订单关闭成功",null);
                        }else{
                            result = new ResultModel(101,  "支付订单关闭失败",null);
                        }
                    }
                }
                System.out.println("交易中心-支付订单关闭结果：" + postResult);
            }else{
                result = new ResultModel(101,  "支付订单关闭失败,不存在的订单编号:" + entity.getOrderNo(),null);
            }
        }catch (Exception ex){
            throw new RuntimeException(ex);
        }
        return result;
    }

    @Override
    public ResultModel updateOrderPayStateService(PayOrder entity){
        ResultModel result = null;
        List<PayOrder> payOrderList = payOrderMapper.findListByParams(entity);
        try {
            if (payOrderList != null && payOrderList.size() > 0) {
                PayOrder payOrder = payOrderList.get(0);
                Date currentDate = new Date();

                // 1 回传同步F6数据
                String payType = (entity.getOrderNo().indexOf("YUNFEI") > -1)?"运费":"补差价";
                String payTime = DateUtil.getNowTime("yyyy-MM-dd HH:mm:ss");
                Map<String,Object> payStateMap = uploadPayMessage(entity.getCompany(), payOrder.getOpenId(), payType, entity.getOrderBillId(), payOrder.getConsumeDetailNo(), payOrder.getMoney(),payTime);
                if(payStateMap != null && !payStateMap.isEmpty()){
                    if(Boolean.valueOf(payStateMap.get("success").toString())){

                        // 2 更新小程序后端支付记录-支付状态。
                        payOrder.setPayState(entity.getPayState());
                        payOrder.setPayResultMsg(entity.getPayResultMsg() + "  " + payStateMap.get("msg").toString());
                        payOrder.setPayTime(currentDate);
                        payOrder.setExpireTime(currentDate);
                        int count = payOrderMapper.updateSelective(payOrder);
                        if(count > 0){
                            result = new ResultModel(100,  "支付订单支付状态更新成功",null);
                        }else{
                            result = new ResultModel(101,  "支付订单支付状态更新失败",null);
                        }
                    }
                }else{
                    result = new ResultModel(101,  "支付订单支付状态更新失败",null);
                }
            }else{
                result = new ResultModel(101,  "支付状态更新失败,不存在的订单编号:" + entity.getOrderNo(),null);
            }
        }catch (Exception ex){
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return result;
    }

    @Override
    public ResultModel returnPayOrderMoneyService(PayOrder entity){
        ResultModel result = null;
        PayOrder searchOrder = new PayOrder();
        String orderNoLike = "%" + entity.getOrderId() + "%";
        searchOrder.setOrderNoLike(orderNoLike);
        List<PayOrder> payOrderList = payOrderMapper.findListByParams(searchOrder);
        try {
            if (payOrderList != null && payOrderList.size() > 0) {
                Company company = entity.getCompany();
                String paramValue = "[";
                for (int i=0;i< payOrderList.size(); i++) {
                    PayOrder payOrder = payOrderList.get(i);
                    String payType = "YUNFEI".equals(payOrder.getGeneratorOrderType())?"运费":"补差价";
                    paramValue +="{\"openId\":\""+ payOrder.getOpenId() +"\",\"refundApplyOperator\":\""+ payOrder.getMobile() +"\",\"refundApplyReason\":\""+entity.getRefundApplyReason() +"\",\"payType\":\""+ payType +"\",\"orderBillId\":\""+ entity.getOrderBillId() +"\",\"refundMoney\":\""+ payOrder.getMoney() +"\"}";
                    if(i != payOrderList.size() -1){
                        paramValue +=",";
                    }
                }
                paramValue += "]";

                // 访问微信退款申请接口，提交退款申请
                StringBuffer params = new StringBuffer();
                params.append("?accountName=" + company.getF6AccountSet()+"&organizationCode="+company.getF6OrganizationCode());
                params.append("&param="+paramValue);
                String postResult = HttpClientUtils.getUri(company.getUrl() + "/orderBaseInfo/refundApply" + params.toString(), null);
                // 解析返回结果
                if(StringUtil.isNotEmpty(postResult)){
                    // 循环更新数据库支付记录结果
                    Map<String,Object>  payMap = JSON.parseObject(postResult);
                    Object msg = payMap.get("msg");
                    for (int i=0;i< payOrderList.size(); i++) {
                        PayOrder payOrder = payOrderList.get(i);
                        if("SUCCESS".equals(msg.toString())) {
                            payOrder.setReturnMoneyState(1);
                        }else{
                            payOrder.setReturnMoneyState(0);
                        }
                        payOrder.setReturnMoneyTime(new Date());
                        payOrder.setReturnMoneyReason(entity.getRefundApplyReason());
                        payOrder.setReturnMoneyResultData(postResult);
                        payOrderMapper.updateByPrimaryKeySelective(payOrder);
                    }
                    if("SUCCESS".equals(msg.toString())){
                        result = new ResultModel(100,  "退款申请成功,支付订单编号:" + entity.getOrderId(),null);
                    }else{
                        result = new ResultModel(101,  "退款申请失败,支付订单编号:" + entity.getOrderId(),null);
                    }
                }
            }else{
                result = new ResultModel(101,  "支付订单发起退款申请功能失败,不存在的支付订单编号:" + entity.getOrderId(),null);
            }
        }catch (Exception ex){
            ex.printStackTrace();
            result = new ResultModel(101,  "支付订单发起退款申请功能异常:" + ex.getMessage(),null);
            throw new RuntimeException(ex);
        }
        return result;
    }

    /**
     * 支付状态更新到F6
     *
     * @param company
     * @param openId
     * @param payType
     * @param orderBillId
     * @param payId
     * @param payMoney
     * @param payTime
     * @return
     * @throws Exception
     *
     * 正式地址：http://118.178.187.230:1880/WeChat.asq?/orderBaseInfo/payInfoAdd
     * 测试地址：http://f6test.feiyang56.cn:1880/WeChat.asq?/orderBaseInfo/payInfoAdd
     */
    private Map<String,Object> uploadPayMessage(Company company, String openId,String payType, String orderBillId ,String payId, double payMoney, String payTime)throws Exception{
        Map<String,Object> resultMap = null;
        // 1 封装参数，调用F6支付状态接口
        StringBuffer params = new StringBuffer();
        params.append("?accountName=" + company.getF6AccountSet()+"&organizationCode="+company.getF6OrganizationCode());
        params.append("&param={\"openId\":\""+ openId +"\",\"payType\":\""+payType+"\",\"orderBillId\":\""+ orderBillId +"\",\"payId\":\""+ payId +"\",\"payMoney\":"+ payMoney +",\"payTime\":\""+ payTime +"\"}");
        String postResult = HttpClientUtils.getUri(company.getUrl() + "/orderBaseInfo/payInfoAdd" + params.toString(), null);
        // 2 解析结果封装返回值
        if(StringUtils.isNotEmpty(postResult)){
            Map<String,Object>  payMap = JSON.parseObject(postResult);
            Object code = payMap.get("code");
            if("200".equals(code.toString())){
                resultMap = new HashMap<String, Object>();
                resultMap.put("success", true);
                resultMap.put("msg", postResult);
            }
        }
        System.out.println("更新F6支付订单状态参    数：==================：" + company.getUrl() + "/orderBaseInfo/payInfoAdd" + params.toString());
        System.out.println("更新F6支付订单状态返回结果：==================：" + postResult);
        return resultMap;
    }

    @Override
    public ResultModel deletePayOrderService(PayOrder entity){
        ResultModel result = null;
        List<PayOrder> payOrderList = payOrderMapper.findListByParams(entity);
        if (payOrderList != null && payOrderList.size() > 0) {
            PayOrder payOrder = payOrderList.get(0);
            Date currentDate = new Date();

            payOrder.setDeleteFlag(1);
            int count = payOrderMapper.updateSelective(payOrder);
            if(count > 0){
                result = new ResultModel(100,  "支付订单删除成功",null);
            }else{
                result = new ResultModel(101,  "支付订单删除成功",null);
            }
        }else{
            result = new ResultModel(101,  "支付订单删除失败,不存在的订单编号:" + entity.getOrderNo(),null);
        }
        return result;
    }

    @Override
    public ResultModel insert(PayOrder entity){
        return null;
    }

    @Override
    public ResultModel insertSelective(PayOrder entity) {
        ResultModel result = null;
        try{
            // 1 查询当前订单的支付订单信息, 查找如果有未支付的订单将其返回。
            PayOrder resultPayOrder = getVaildatePayOrderTimeOut(entity);
            // 2 获取支付订单支付签名数据信息
            if(resultPayOrder == null) {
                // 获取code关联对象信息
                MiniProgram miniProgram = entity.getMiniProgram();
                Company company = entity.getCompany();
                // 1 封装参数，访问交易中心统一下单接口
                Map<String, String> params = Maps.newHashMap();
                params.put("password", company.getTenantPass());
                params.put("loginName", company.getCode());
                params.put("consumeTypeCode", "daikou");          // 消费项目编码 entity.getGoodsDescribe()
                params.put("sources", "22");                        // 支付方式{1支付宝, 2微信, 11支付宝APP, 12微信APP, 22微信小程序}
                params.put("money", entity.getMoney() + "");
                params.put("remark", entity.getRemark());
                params.put("extraParam", "{\"openId\":\"" + entity.getOpenId() + "\"}");
                System.out.println(params.toString());
                String postResult = HttpClientUtils.post(miniProgram.getTradingcenterUrl() + "/consumeDetailManager/addConsumeRecharge", params, null, 20000, 20000);

                if (StringUtils.isNotEmpty(postResult)) {
                    // 2 解析统计下单返回信息，封装PayOrder数据保存到数据库
                    Map<String, Object> resultMap = JSON.parseObject(postResult);
                    Object success = resultMap.get("success");
                    if (Boolean.valueOf(success.toString())) {
                        Map<String, Object> objectMap = JSON.parseObject(resultMap.get("object").toString());
                        if (objectMap != null && !objectMap.isEmpty()) {
                            // 获取微信支付平台 支付信息
                            Map<String, Object> onLinePayResultMap = JSON.parseObject(objectMap.get("onLinePayResult").toString());
                            if (onLinePayResultMap != null && !onLinePayResultMap.isEmpty()) {
                                String returnCode = onLinePayResultMap.get("returnCode").toString();
                                if ("SUCCESS".equals(returnCode)) {
                                    entity.setPrepayId(onLinePayResultMap.get("responseBody").toString());
                                    entity.setOutTradeNo(onLinePayResultMap.get("outTradeNo").toString());
                                }
                            }
                            entity.setConsumeDetailNo(objectMap.get("consumeDetailNo").toString());
                            entity.setRequestCreateData(params.toString());
                            entity.setPayType(22);
                            entity.setPayResultMsg(postResult);
                            entity.setPayState(0);
                            entity.setCloseState(0);
                            entity.setDeleteFlag(0);
                            entity.setCreateTime(new Date());
                            entity.setStartTime(new Date());
                            int count = payOrderMapper.insertSelective(entity);
                            if (count > 0) {
                                // 获取生成调启微信支付签名数据
                                Map<String, Object> signMap = getTradingcenterPaySign(entity.getOrderNo(), entity.getPrepayId());
                                result = new ResultModel(100, "微信统一下单成功", signMap);
                            } else {
                                result = new ResultModel(101, "微信统一下单失败", null);
                            }
                        }
                    } else {
                        result = new ResultModel(101, resultMap.get("message").toString(), null);
                    }
                }
                System.out.println("统一下单接口addConsumeRecharge请求参数：" + params.toString());
                System.out.println("统一下单接口addConsumeRecharge返回内容：" + postResult);
            }else{
                // 获取生成调启微信支付签名数据
                Map<String, Object> signMap = getTradingcenterPaySign(resultPayOrder.getOrderNo(), resultPayOrder.getPrepayId());
                result = new ResultModel(100, "微信统一下单成功", signMap);
            }

        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 验证未支付订单是否超时, 若超时将其删除并重新生成支付订单号码
     *
     * @param entity
     * @return
     */
    public PayOrder getVaildatePayOrderTimeOut(PayOrder entity){
        PayOrder resultPayOrder = null;
        PayOrder searchOpayOrder = new PayOrder();
        searchOpayOrder.setOrderNoLike("%"+entity.getOrderId()+"%");
        List<PayOrder> payOrderList = payOrderMapper.findListByParams(searchOpayOrder);
        for (PayOrder payOrder:payOrderList) {
            if(payOrder.getPayState()==0){

                // 1 验证未支付订单，运费与差额是否更改过。
                boolean moneyChange = getPayOrderMoneyChange(payOrder.getCode(), entity.getOrderBillId(), payOrder.getGeneratorOrderType(), payOrder.getMoney());
                // 判断若订单在30分钟内未支付，且F6端没有改变运费金额  则返回订单支付信息。
                if(DateUtil.getTimeByMinute(payOrder.getStartTime(),30 ).getTime() > new Date().getTime() && moneyChange == false){
                    resultPayOrder = payOrder;
                    break;
                }else{
                    // 删除数据库中当前订单的支付订单信息
                    payOrder.setOrderNo("delete");
                    payOrder.setDeleteFlag(1);
                    payOrderMapper.updateByPrimaryKeySelective(payOrder);
                    String payOrderNo = getPayOrderNotByParamsService(entity.getOrderId());
                    if(StringUtil.isNotEmpty(payOrderNo)) {
                        if(payOrderNo.indexOf("YUNFEI") > -1) {
                            entity.setGeneratorOrderType("YUNFEI");
                        }
                        if(payOrderNo.indexOf("CHAJIA") > -1) {
                            entity.setGeneratorOrderType("CHAJIA");
                        }
                        entity.setOrderNo(payOrderNo);
                    }
                }
            }
        }
        return resultPayOrder;
    }


    /**
     * 验证支付订单金额 是否被F6平台变更过
     *
     * @param code
     * @param orderBillMasterId
     * @return
     */
    public boolean getPayOrderMoneyChange(String code, String orderBillMasterId, String orderPayType, Double money){
        boolean result = false;
        Map<String, Object> moneyMap = iOrderService.getOrderF6PayStateInfomaction(code, orderBillMasterId);
        if(moneyMap != null && !moneyMap.isEmpty()){
            Double transportCostValue = 0D;
            Double hBackupMoney1Value = 0D;
            String costValue = "";String moneyValue = "";
            try{
                costValue = moneyMap.get("totalTransportCost") == null ? "" : moneyMap.get("totalTransportCost").toString();
                if(StringUtil.isNotEmpty(costValue)){
                    transportCostValue = Double.parseDouble(costValue);
                }
            }catch (Exception e){}
            try{
                moneyValue = moneyMap.get("hBackupMoney1") == null ? "" : moneyMap.get("hBackupMoney1").toString();
                if(StringUtil.isNotEmpty(moneyValue)){
                    hBackupMoney1Value = Double.parseDouble(moneyValue);
                }
            }catch (Exception e){}
            if("YUNFEI".equals(orderPayType)){
                if(transportCostValue > 0){
                    result = money != transportCostValue ? true : false ;
                }
            }else if("CHAJIA".equals(orderPayType)){
                if(hBackupMoney1Value > 0){
                    result = money != hBackupMoney1Value ? true : false ;
                }
            }
            System.out.println("验证支付订单金额是否更改-参数：  code: " + code + " orderBillMasterId:" + orderBillMasterId + " orderPayType:" + orderPayType + " money: " + money);
            System.out.println("要验证的金额与返回值：   money: " + money + " totalTransportCost:" + costValue + " hBackupMoney1:" + moneyValue);
        }
        return result;
    }

    /**
     * 获取微信待支付订单 发起支付数据信息
     *
     * @param entity
     * @return
     */
    @Override
    public ResultModel getPayOrderSignCodeService(PayOrder entity){
        ResultModel result = null;
        PayOrder searchOpayOrder = new PayOrder();
        searchOpayOrder.setOrderNoLike("%"+entity.getOrderId()+"%");
        List<PayOrder> payOrderList = payOrderMapper.findListByParams(searchOpayOrder);
        if (payOrderList != null && payOrderList.size() > 0) {
            PayOrder resultPayOrder = null;
            for (PayOrder payOrder : payOrderList) {
                if(0 == payOrder.getPayState()){
                    resultPayOrder = payOrder;
                    break;
                }
            }
            // 获取生成调启微信支付签名数据
            if(resultPayOrder != null){
                Map<String, Object> signMap = getTradingcenterPaySign(resultPayOrder.getOrderNo(), resultPayOrder.getPrepayId());
                result = new ResultModel(100,  "支付订单签名数据获取成功", signMap);
            }else{
                result = new ResultModel(101,  "无待支付订单信息。", null);
            }
        }else{
            result = new ResultModel(101,  "支付订单签名数据获取失败,不存在的订单编号:" + entity.getOrderNo(),null);
        }
        return result;
    }

    /**
     * 转换微信签名数据，进行封装
     *
     * @param payOrderNo
     * @param signContent
     * @return
     */
    public Map<String, Object> getTradingcenterPaySign(String payOrderNo, String signContent){
        Map<String, Object> result = null;
        Map<String, Object> parseMap = JSON.parseObject(signContent);
        if(parseMap != null && !parseMap.isEmpty()){
            result = parseMap;
            result.put("payOrderNo", payOrderNo);
            result.put("package", parseMap.get("pkg"));
        }
        return result;
    }

    /**
     * 生成微信支付签名数据
     *
     * @param appId
     * @param nonceStr
     * @param payPackage
     * @param timeStamp
     * @param mchKey
     * @param payOrderNo
     * @return
     */
    private Map<String, String> getGeneratorPaySign(String appId, String nonceStr, String payPackage, String timeStamp, String mchKey, String payOrderNo){
        // 生成paySign 签名信息
        String signContent = ("appId="+ appId +"&nonceStr="+ nonceStr + "&package="+payPackage + "&signType=MD5&timeStamp=" + timeStamp + "&key=" + mchKey);
        String paySign =  MD5Util.getMD5Code(signContent).toUpperCase();

        // 将签名信息封装Map进行返回
        Map<String, String> result = Maps.newHashMap();
        result.put("timeStamp", timeStamp);
        result.put("nonceStr", nonceStr);
        result.put("package", payPackage);
        result.put("signType", "MD5");
        result.put("paySign",paySign);
        result.put("payOrderNo",payOrderNo);
        return result;
    }

    @Override
    public ResultModel update(PayOrder entity) {
        return null;
    }

    @Override
    public ResultModel updateSelective(PayOrder entity) { return null; }

    @Override
    public ResultModel delete(Long id) {
        return null;
    }

    @Override
    public ResultModel delete(PayOrder entity) {
        return null;
    }

    @Override
    @Transactional(readOnly = true)
    public List<PayOrder> findList(PayOrder entity) {
        return payOrderMapper.findList(entity);
    }

    @Override
    public String getPayOrderNotByParamsService(String payOrderNo){
        String result = "";
        if(payOrderNo.indexOf("YUNFEI") > -1 || payOrderNo.indexOf("CHAJIA") > -1){
            result = payOrderNo;
        }else{
            PayOrder searchPayOrder = new PayOrder();
            searchPayOrder.setOrderNoLike(payOrderNo+"%");
            List<PayOrder> payOrders = payOrderMapper.findListByParams(searchPayOrder);
            String[] resultNoArray = {payOrderNo+"-YUNFEI",payOrderNo+"-CHAJIA"};

            // 循环涮选返回订单ID
            for(String resultNo:resultNoArray){
                boolean isResult = true;
                for(int i=0; i<payOrders.size();i++){
                    PayOrder temp = payOrders.get(i);
                    if(resultNo.equals(temp.getOrderNo())){
                        isResult = false;
                    }
                }
                if(isResult == true){
                    result = resultNo;
                    break;
                }
            }
        }
        return result;
    }

    @Override
    public List<PayOrder> findPayOrderByParamsService(String payOrderNo){
        PayOrder searchPayOrder = new PayOrder();
        searchPayOrder.setOrderNoLike(payOrderNo+"%");
        return payOrderMapper.findListByParams(searchPayOrder);
    }

    @Override
    public void vaildateOrdersPayStateService(List<Order> orders){
        // 循环订单信，获取订单支付信息，并更新订单支付状态
        if(orders != null  && orders.size() > 0){
            for (Order order: orders) {
                validatePayOrderPayState(order);
            }
        }
    }

    /**
     * 验证支付订单支付状态，并回更支付信息到F6平台
     *
     * @param order
     */
    @Override
    public void validatePayOrderPayState(Order order){
        if(order != null){
            // 1 循环查询订单数据库支付订单信息。
            PayOrder searchPayOrder = new PayOrder();
            searchPayOrder.setOrderNoLike("%"+ order.getId() +"%");
            List<PayOrder> payOrders = payOrderMapper.findListByParams(searchPayOrder);
            for (PayOrder payOrder : payOrders) {
                // 判断订单未支付，则查询交易中心状态，若不相同则更新支付状态
                if(payOrder.getPayState() == 0) {
                    MiniProgram miniProgram = iMiniProgramService.selectByCode(payOrder.getCode());
                    Company company = iCompanyInfoService.getCompanyByCode(payOrder.getCode());
                    try {
                        // 1 查询交易中心 订单状态
                        Map<String, String> params = Maps.newHashMap();
                        params.put("password", company.getTenantPass());
                        params.put("loginName", company.getCode());
                        params.put("consumeDetailNo", payOrder.getConsumeDetailNo());
                        String postResult = HttpClientUtils.post(miniProgram.getTradingcenterUrl() + "/consumeDetailManager/queryTradeDetail", params, null, 10000, 10000);
                        if (StringUtils.isNotEmpty(postResult)) {
                            Map<String, Object> resultMap = JSON.parseObject(postResult);
                            Object success = resultMap.get("success");
                            if (Boolean.valueOf(success.toString())) {
                                // 获取对象中支付信息内容
                                Map<String,Object> objectMap = JSON.parseObject(resultMap.get("object").toString());
                                if(objectMap != null && !objectMap.isEmpty()){

                                    // 验证交易中心支付状态，根据状态更新支付信息到F6系统中
                                    Integer stateFlag = objectMap.get("stateFlag")!= null? Integer.parseInt(objectMap.get("stateFlag").toString()):0;
                                    if(999 == stateFlag){

                                        Date currentDate = new Date();
                                        // 1 回传同步F6数据
                                        String payType = (payOrder.getOrderNo().indexOf("YUNFEI") > -1)?"运费":"补差价";
                                        String payTime = DateUtil.getNowTime("yyyy-MM-dd HH:mm:ss");
                                        Map<String,Object> payStateMap = uploadPayMessage(company, payOrder.getOpenId(), payType, order.getOrderBillMasterId(), payOrder.getConsumeDetailNo(), payOrder.getMoney(),payTime);
                                        if(payStateMap != null && !payStateMap.isEmpty()){
                                            if(Boolean.valueOf(payStateMap.get("success").toString())){
                                                // 2 更新小程序后端支付记录-支付状态。
                                                payOrder.setPayState(1);
                                                payOrder.setPayResultMsg("详情页-更新支付状态  " + payStateMap.get("msg").toString());
                                                payOrder.setPayTime(currentDate);
                                                payOrder.setExpireTime(currentDate);
                                                payOrderMapper.updateSelective(payOrder);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    public List<PayOrder> getPayOrderListByOrderIdService(String orderId){
        PayOrder searchPayOrder = new PayOrder();
        searchPayOrder.setOrderNoLike("%"+ orderId +"%");
        return payOrderMapper.findListByParams(searchPayOrder);
    }


}
